<template>
  <div class="profile-info-container">
    <el-card class="profile-info-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="100px"
        class="profile-form"
      >
        <!-- 头像上传 -->
        <el-form-item label="头像" class="avatar-item">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleAvatarChange"
            :before-upload="beforeUpload"
            :limit="1"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <!-- 基本信息 -->
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" disabled />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <!-- 修改密码 -->
        <!-- <div class="password-section">
          <div class="section-title">修改密码</div>
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
              v-model="userForm.oldPassword"
              type="password"
              placeholder="请输入原密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="userForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="userForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>
        </div> -->

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading"> 保存修改 </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getUserInfo, updateUserInfo } from '@/api/user'
import { uploadAvatar } from '@/api/upload'
import type { UploadFile, FileItem } from '@/types/upload'
import { v4 as uuidv4 } from 'uuid'

const userStore = useUserStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const userForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
})

const singleFile = reactive<FileItem>({
  uid: '',
  name: '',
  status: 'ready',
})

const rules = reactive<FormRules>({
  nickname: [
    { required: false, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  email: [
    { required: false, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  phone: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const { data } = await getUserInfo()
    Object.assign(userForm, {
      username: data.data.username,
      nickname: data.data.nickname || '',
      email: data.data.email || '',
      phone: data.data.phone || '',
      avatar: data.data.avatar || '',
    })
    userStore.updateUserDetails(data.data)
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 文件上传前的验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarChange = (file: UploadFile) => {
  if (!beforeUpload(file.raw)) return

  // 创建预览URL
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = async () => {
    Object.assign(singleFile, {
      uid: uuidv4(),
      name: file.name,
      url: reader.result as string,
      status: 'ready',
      raw: file.raw,
    })

    try {
      if (!singleFile.raw) {
        ElMessage.error('请选择文件')
        return
      }

      singleFile.status = 'uploading'
      singleFile.percentage = 0

      const response = await uploadAvatar(singleFile.raw, (percentage) => {
        singleFile.percentage = percentage
      })

      singleFile.status = 'success'
      userForm.avatar = response.data.data.url
      ElMessage.success('上传成功')
    } catch (error) {
      singleFile.status = 'error'
      ElMessage.error('上传失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await updateUserInfo({
          nickname: userForm.nickname,
          email: userForm.email,
          phone: userForm.phone,
          avatar: userForm.avatar,
        })
        ElMessage.success('更新成功')
        // 更新store中的用户信息
        await fetchUserInfo()
      } catch (error) {
        ElMessage.error('更新失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  fetchUserInfo()
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile-info-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.profile-info-card {
  margin-top: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-form {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

.avatar-uploader:hover .avatar-uploader-icon {
  border-color: #409eff;
  color: #409eff;
}

.password-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.section-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
}
</style>
